#include "54func.h"
#include "serverFunc.h"
#include "assistFuncServer.h"
#include "log.h"

int userDel(MYSQL* conn, int netfd, const cmd_t *pcmd){
    char sql[1024] = {0};
    char salt[21] = {0};
    char* encryptedPassword = (char*)calloc(256, sizeof(char));
    sprintf(sql, "select salt,encrypted_password,tomb from user where "
            "name = '%s';", pcmd->argv1);
    mysql_query(conn, sql);
    SQL_LOG(conn);

    MYSQL_RES* res;
    MYSQL_ROW row;
    res = mysql_store_result(conn);
    if(mysql_num_rows(res) == 0) {
        errorSend(netfd, NULL);
        errorSend(netfd, "用户不存在!");
    }
    else {
        row = mysql_fetch_row(res);
        memcpy(salt, row[0], sizeof(salt));
        encryptedPassword = crypt(pcmd->argv2, salt);
        encryptedPassword[255] = '\0';
        // 先判断是否已经注销
        if(row[2][0] == '1'){
            //已经注销
            errorSend(netfd,NULL);
            errorSend(netfd,"用户已注销!\n");
            return 0;
        }
        // 用户未注销
        if(strncmp(row[1], encryptedPassword, strlen(encryptedPassword)) == 0){
            mysql_free_result(res);
            memset(sql, 0, sizeof(sql));
            sprintf(sql, "update user set tomb = 1 where name = '%s';", pcmd->argv1);
            mysql_query(conn,sql);
            successSend(netfd);
            SQL_LOG(conn);
        }
        else {
            errorSend(netfd, NULL);
            errorSend(netfd, "密码错误!");
        }
    }
    return 0;
}

